<?php
/**
 * @param number $type 默认是数字 
 * @param number $length 默认4位长度
 * @param string $codeName verifyCode
 * @param number $pixel 100个点
 * @param number $line 0个直线
 * @param number $arc 0个弧
 * @param number $width 画布宽度
 * @param number $height 画布高度
 * @param unknown $fontfiles 字体库
 * @return number
 */
function getVerify($type = 1, $length = 4, $width = 200, $height = 40,$codeName = 'verifyCode', $pixel = 100, $line = 0, $arc = 0,  $fontfiles = array('fonts/simfang.ttf','fonts/simhei.ttf')) {
	$image = imagecreatetruecolor ( $width, $height );
	function randColor($image) {
		return imagecolorallocate ( $image, mt_rand ( 0, 255 ), mt_rand ( 0, 255 ), mt_rand ( 0, 255 ) );
	}
	$white = imagecolorallocate ( $image, 255, 255, 255 );
	imagefilledrectangle ( $image, 0, 0, $width, $height, $white );
	switch ($type) {
		case 1 :
			// 数字
			$string = join ( '', array_rand ( range ( 0, 9 ), $length ) );
			break;
		case 2 :
			// 字母
			$string = join ( '', array_rand ( array_flip ( array_merge ( range ( 'a', 'z' ), range ( 'A', 'Z' ) ) ), $length ) );
			break;
		case 3 :
			// 数字+字母
			$string = join ( '', array_rand ( array_flip ( array_merge ( range ( 'a', 'z' ), range ( 'A', 'Z' ), range ( 0, 9 ) ) ), $length ) );
			break;
		case 4 :
			// 汉字
			$str = "时,间,跨,度,发,牢,骚,京,东,方,科,技,实,力,可,见,味,儿,为,了,抗,日,将,领,万,科,进,入,了,口,味,加,入,了,速,递,否,石,佛,思,考,的,房,间,里,看,似,简,单,风,口,浪,尖,遛,弯,儿,破,我,诶,人,品";
			$arr = explode ( ',', $str );
			$string = join ( '', array_rand ( array_flip ( $arr ), $length ) );
			break;
	}
	// 将验证码存储到SESSION中
	session_start ();
	$_SESSION [$codeName] = $string;
	for($i = 0; $i < $length; $i ++) {
		$fontfile = $fontfiles [array_rand ( $fontfiles )];
		//mb_string库
		$char = mb_substr ( $string, $i, 1, 'utf-8' );
		imagettftext ( $image, mt_rand ( 14, 24 ), mt_rand ( - 30, 30 ),  20+ $i*50, mt_rand ( $height -20, $height - 10 ), randColor ( $image ), $fontfile, $char );
	}
	// 检测是否设置干扰元素
	if ($pixel) {
		for($i = 1; $i <= $pixel; $i ++) {
			imagesetpixel ( $image, mt_rand ( 0, $width ), mt_rand ( 0, $height ), randColor ( $image ) );
		}
	}
	if ($line) {
		for($i = 1; $i <= $line; $i ++) {
			imageline ( $image, mt_rand ( 0, $width ), mt_rand ( 0, $height ), randColor ( $image ) );
		}
	}
	if ($arc) {
		for($i = 1; $i <= $arc; $i ++) {
			imagearc ( $image, mt_rand ( 0, $width / 2 ), mt_rand ( 0, $height / 2 ), mt_rand ( 0, $width ), mt_rand ( 0, $height ), mt_rand ( 0, 360 ), mt_rand ( 0, 360 ), randColor ( $image ) );
		}
	}
	header ( 'content-type:image/png' );
	imagepng ( $image );
	imagedestroy ( $image );
}